/**
 * @file fastus_cd22_485.h
 * @details fastus 点激光位移传感器控制代码，实现了基本的功能。
 * @copyright 北京经海科技有限公司
 * @author 李渊 <18069211@qq.com>
 * @version 1.0
 * @date 2017.02.05
 */

#ifndef FASTUS_CD22_485_H
#define FASTUS_CD22_485_H

#include <QObject>
#include <QSerialPort>
#include <stdint.h>

class FASTUS_CD22_485: public QObject
{
    Q_OBJECT
public:
    FASTUS_CD22_485(QObject *parent = 0);
signals:
    /**
     * @brief dataReceived
     * @param data 收到的数据
     */
    void dataReceived(int16_t data);
    /**
     * @brief judgementReceived
     * @param judgement 判定结果
     */
    void judgementReceived(bool judgement);
    /**
     * @brief commandAcknowledged 表明当前命令已经被传感器接收了。
     */
    void commandAcknowledged();
    /**
     * @brief commError
     * @param error_code 错误代码表
     *          02H 地址错误
     *          04H BCC 值错误
     *          05H 发送的命令不是[C]/[W]/[R] 格式的命令
     *          06H 设定值错误（参数格式错误）
     *          07H 设定值错误（超出设定值范围）
     */
    void commError(char error_code);

    void readParaReceived(int16_t data);
    void writeFinished();

public slots:
    /**
     * @brief cmdRead 调用一次这个函数，传感器回传一组数据
     */
    void cmdRead();
    void cmdJudge();
    void cmdSaveSettings();
    void cmdUndoSettings();
    /**
     * @brief cmdLaserOn 打开传感器激光器输出
     */
    void cmdLaserOn();
    /**
     * @brief cmdLaserOff 关闭传感器激光器输出
     */
    void cmdLaserOff();
    void cmdInit();
    void cmdLock();
    void cmdUnlock();
    void cmdZero();
    void cmdUnzero();
    void readFarEndThreshold();
    void readNearEndThreshold();
    void writeFarEndThreshold(int16_t data);
    void writeNearEndThreshold(int16_t data);
    void writeSamplePeriod(int16_t data);
    void readSamplePeriod();
    void readAveragePara();
    void writeAveragePara(int16_t data);
    void readSensibility();
    void writeSensibility(int16_t data);
private:
    QSerialPort m_reader;
    enum STATE{ STATE_IDLE,
                STATE_STX,
                STATE_ACK,
                STATE_NAK,
                STATE_DATA1,
                STATE_DATA2,
                STATE_ETX,
                STATE_BCC};
    enum STATE m_state;
    char m_message[3];
    enum CMOMMAND{ CMD_READ,
                   CMD_JUDGE,
                   CMD_ACK0000,
                   CMD_READ_PARA,
                   CMD_WRITE_STAGE1,
                   CMD_WRITE_STAGE2,
                   CMD_IDLE };
    char m_command;
    int16_t m_data;
    void stateMachine(char c);
    void inStateETX(char c);
    void inStateSTX(char c);
    void dispatchData(int16_t data);
    void cmd_C(char c1, char c2);
    void cmd_R(char c1, char c2);
    void cmd_W(char c1, char c2);


private slots:
    void readCom();
};

#endif // FASTUS_CD22_485_H
